<template>
  <div class="work-detail-container">
    <a-row type="flex" justify="center" v-if="template">
      <a-col :span="8" class="cover-img">
        <img :src="template.coverImg" alt="" />
      </a-col>
      <a-col :span="8">
        <h2>{{ template.title }}</h2>
        <p>{{ template.title }}</p>
        <div class="author">
          <a-avatar>V</a-avatar>
          该模版由 <b>{{ template.author }}</b> 创作
        </div>
        <div class="bar-code-area">
          <span>扫一扫，手机预览</span>
          <canvas ref="container"></canvas>
        </div>
        <div class="use-button">
          <router-link to="/editor">
            <a-button type="primary" size="large"> 使用模版 </a-button>
          </router-link>
          <a-button size="large"> 下载图片海报 </a-button>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup name="TemplateDetail">
import { computed,ref, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { workInfos } from '@/stores/work'
import pinia from '@/stores/index'
import QRCode from 'qrcode'

const baseH5URL ='http://localhost:7006/api/utils'
const workInfoStore = workInfos(pinia)
const route = useRoute()
const container = ref<null | HTMLElement>(null)
const currentId = route.params.id  as string
const template = computed(() => workInfoStore.getTemplateById(parseInt(currentId)))

const channelURL = computed(() => `${baseH5URL}/p/${template.value?.id}-${template.value?.uuid}`)

const generateQRCode = async () => {
  (container.value as HTMLElement).innerHTML =''
    try {
        await QRCode.toCanvas(container.value, channelURL.value, { width: 100 })
    } catch (err) {
        console.error(err)
    }
}

onMounted(async() => {

  await workInfoStore.fetchTemplate(parseInt(currentId))
  await nextTick()
  generateQRCode()
})
</script>

<style scoped>
.work-detail-container {
  margin: 50px auto;
  min-height: 80vh;
}

.cover-img {
  margin-right: 30px;
}

.cover-img img {
  width: 100%;
}

.use-button {
  margin: 30px 0;
}

.ant-avatar {
  margin-right: 10px;
}

.bar-code-area {
  margin: 20px 0;
}
</style>
